import {
	RouterMount,
	createRouter
} from 'uni-simple-router';

let num = 0;
const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	routerErrorEach: (error, router) => {
	    // uni-simple-router把uniapp默认的退出应用的效果给拦截了，因此需要手动单独处理一下
	    if (error.uniActualData.from === 'backbutton') {
			num++;
			if (num > 1) {
				plus.runtime.quit();
			} else {
				plus.nativeUI.toast('再按一次退出应用');
			}
			setTimeout(() => {
				num = 0;
			}, 1500);
	    }
	    // 路由跳转解锁，否则首页点击物理返回键后，路由锁定，跳转失败...
	    if (error.type === 3) {
	      router.$lockStatus = false;
	    }
	},
	routes: [
		...ROUTES,
		{
			path: '*',
			redirect: (...args) => {
				return {
					name: '404',
				}
			}
		},
	]
});

//全局路由前置守卫
router.beforeEach(async (to, from, next) => {
	// console.log(to, '路由前置守卫beforeEach==========================');
	let token = uni.getStorageSync("newToken");
	if (to.meta.auth && to.meta.auth === true) {
		console.log('to.meta.auth',to.meta.auth)
		if (token) {
			next();
		} else {
			// console.log('跳转到登录页面========');
			next({
				name: 'login_login',
				params: {
					from: to.path
				},
				NAVTYPE: 'push'
			});
		}
	} else {
		// console.log("不需要登录");
		next();
	}
});

router.afterEach((to, from, next) => {
	//写点什么
});

export {
	router,
	RouterMount
}